package com.seocoo.worker.home;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

import com.seocoo.worker.R;
import com.seocoo.worker.base.Const;
import com.seocoo.worker.base.entity.ELogin;
import com.seocoo.worker.base.entity.EUserInfoBean;
import com.seocoo.worker.order.OrderHomeGoldFragment;
import com.seocoo.worker.order.OrderHomeStarFragment;
import com.seocoo.worker.user.model.UserModel;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.mvvm.LiveDataMatch;
import com.sfh.lib.ui.MVVMFragment;

/**
 * 功能描述:
 *
 * @author
 * @date 2020/2/16
 */
public class HomeFragment extends MVVMFragment {

    private EUserInfoBean mInfoBean;
    private Fragment oldFragment;

    @Override
    public int getLayout() {
        return R.layout.home_fragment;
    }

    @Override
    public void initData(View view) {
        ELogin login = AppCacheManager.getCacheListener().getObject(Const.LOGIN_KEY, ELogin.class);
        this.onUserInfo(login.getUserInfo());
    }

    @Override
    public void onResume() {
        super.onResume();
        this.getViewModel(UserModel.class).getUserInfo();
    }

    @LiveDataMatch
    public void onUserInfo(EUserInfoBean infoBean) {
        if (mInfoBean != null && mInfoBean.getCraftsmanType() == infoBean.getCraftsmanType()) {
            //工匠级别没有变化
            return;
        }

        this.mInfoBean = infoBean;
        FragmentManager manager = getChildFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        if (oldFragment != null) {
            Fragment old = oldFragment;
            transaction.detach(old);
        }
        if (infoBean.getCraftsmanType() == 1) {
            // 金牌工匠
            oldFragment = Fragment.instantiate(getContext(), OrderHomeGoldFragment.class.getName(), null);
            transaction.add(R.id.homeContainer, oldFragment);

        } else {
            //星级工匠
            oldFragment = Fragment.instantiate(getContext(), OrderHomeStarFragment.class.getName(), null);
            transaction.add(R.id.homeContainer, oldFragment);
        }

        transaction.commitAllowingStateLoss();

    }
}
